﻿using AuSys.Models.Identities;
using AuSys.Repos.Identities;
using AuSys.Services.App.ActionFilters;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;

namespace AuSys.Controllers.Identities
{
    [Authorize]
    [ApiController]
    [Route(ApiConsts.routePattern)]
    public class UserController(
        UserRepo userRepo
        ) : ControllerBase, IAccessCheckController
    {
        [HttpGet]
        public List<UserDto> Index()
        {
            return userRepo.IndexUser();
        }
        [HttpGet]
        [UserAccess(getChildrenAccess)]
        public List<UserDto> GetChildren(int id)
        {
            return userRepo.GetChildren(id);
        }
        [HttpPost]
        [UserAccess(createUserAccess)]
        [UserTypeRestricted(UserType.Member)]
        public bool Create([FromBody]UserDto user)
        {
            userRepo.CreateUser(user);
            return true;
        }
        [HttpPut]
        [UserAccess]
        [UserTypeRestricted(UserType.Member)]
        public bool Update([FromBody]UserDto user)
        {
            userRepo.UpdateUser(user);
            return true;
        }
        [HttpDelete]
        [UserTypeRestricted(UserType.Admin)]
        public bool Delete(int id)
        {
            userRepo.DeleteUser(id);
            return true;
        }


        [NonAction]
        public AccessibleUserIds GetAccessibleUserIds(
            object obj, string? policy = null)
        {
            if (obj is int num)
            {
                if(policy == getChildrenAccess)
                {
                    if (num == 0)
                        return AccessibleUserIds.Pass();
                }
                return new([num]);
            }
            else if (obj is UserDto user)
            {
                if (policy == createUserAccess)
                {
                    //“创建用户”policy下，需验证“父级Id”是否有权限
                    var parentId = user.ParentId;
                    if (parentId == 0)
                        return AccessibleUserIds.Pass();
                    return new([parentId]);
                }
                return new([user.Id]);
            }
            throw new NotImplementedException();
        }
        private const string createUserAccess = nameof(createUserAccess);
        private const string getChildrenAccess = nameof(getChildrenAccess);
    }
}
